package cn.yanxiaohui.common.util;

import java.util.Random;

/**
 * 简单的加密解密工具类
 * @author yanxh
 *
 */
public class DecoderOrEncoderUtils {
	
	/** 加密前缀长度 **/
	public static final int PREFIX_LENGTH = 5;
	
	/** 加密后缀长度 **/
	public static final int SUFFIX_LENGTH = 5;
	
	/**
	 * 字符串加密
	 * 1.前缀+字符串+后缀
	 * 2.整体反转
	 * @param password 指定字符串
	 * @return 加密后字符串
	 */
	public static String getEncoderStr(String password) {
		if(password == null || password.trim().length() == 0) {
			return null;
		}
		StringBuffer buffer = new StringBuffer();
		buffer.append(getRandStr(PREFIX_LENGTH)).append(password).append(getRandStr(SUFFIX_LENGTH));
		return buffer.reverse().toString();
	}
	
	/**
	 * 字符串解密
	 * 1.字符串反转
	 * 2.去掉前缀、后缀
	 * @param password 指定字符串
	 * @return 解密后字符串
	 */
	public static String getDecoderStr(String password) {
		if(password == null || password.trim().length() == 0) {
			return null;
		}
		StringBuffer buffer = new StringBuffer(password);
		String reverse = buffer.reverse().toString();
		if(reverse.length() > PREFIX_LENGTH) {
			reverse = reverse.substring(PREFIX_LENGTH, reverse.length());
		}
		if(reverse.length() > SUFFIX_LENGTH) {
			reverse = reverse.substring(0, reverse.length() - SUFFIX_LENGTH);
		}
		return reverse.toString();
	}
	
	/**
	 * 获取指定长度的随机数
	 * @param length 指定长度
	 * @return 随机数
	 */
	public static String getRandStr(int length) {
		if(length <= 0) {
			return "";
		}
		Random random = new Random();
		StringBuffer buffer = new StringBuffer();
		for(int i=0; i< length; i++) {
			buffer.append(random.nextInt(10));
		}
		return buffer.toString();
	}
}
